package wechat.rcv.cosuming;

import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.shrcl.engineerprocess.domain.CorpWeChatUser;
import com.shrcl.engineerprocess.domain.CorpWeChatUserDAO;

import wechat.rcv.RcvToken;

import edu.fudan.mylang.utils.DateUtil;

@Component
public class EventSubscribeConsuming implements IMsgConsuming {
	final static Logger logger = Logger.getLogger(EventSubscribeConsuming.class.getName());
	private RequestObj req;
	@Autowired
	CorpWeChatUserDAO corpWeChatUserDAO;
//	<xml>
//	<ToUserName><![CDATA[toUser]]></ToUserName>
//	<FromUserName><![CDATA[FromUser]]></FromUserName>
//	<CreateTime>123456789</CreateTime>
//	<MsgType><![CDATA[event]]></MsgType>
//	<Event><![CDATA[subscribe]]></Event>
//	</xml>
	public EventSubscribeConsuming() {
	}
	@Override
	public String acceptSync() {
		String res_str = "欢迎您加入企业号!";
		String wechatid =req.getFromUserName();
		if (!addWechatUser(wechatid)){
			res_str = "未知客户" + ", "+res_str;
		}
		return createMsg(wechatid,res_str);
	}

	@Override
	public String acceptAsync() {
		return acceptSync();
	}
	@Override
	public void setRequestObj(RequestObj ro) {
		// TODO Auto-generated method stub
		req = ro;
	}
	private Boolean addWechatUser( String wechatid){
		try {
			logger.info("wechatid*********** "+wechatid);
			CorpWeChatUser wu = corpWeChatUserDAO.findWeChatUser(wechatid);
			assertNotNull(wu);
			wu.setExcluded(false);
			wu.setRegisterDate(DateUtil.now());	
			return true;
		}
		catch (RuntimeException e){
			e.printStackTrace();
			logger.info("failed to find wechat by wechatid");
			return false;
		}
	}
//	private String getCustomerNameByCode(String customercode){
//		try {
//			return assertNotNull(customerDAO.findByCode(customercode)).getName();
//		}
//		catch (RuntimeException e){
//			logger.info("failed to find customer by code");
//			return "未知客户";
//		}
//	}
	private <T> T assertNotNull(T t){
		if(t==null) throw new RuntimeException();
		return t;
	}
	private String createMsg(String ToUserName, String content) {
		String format = "<xml>\n" + "<ToUserName><![CDATA[%1$s]]></ToUserName>\n"
				+ "<FromUserName><![CDATA[%2$s]]></FromUserName>\n" + "<CreateTime>%3$s</CreateTime>\n"
				+ "<MsgType><![CDATA[%4$s]]></MsgType>\n" + "<Content><![CDATA[%5$s]]></Content>\n" + "</xml>";

		String createTime = Long.toString(new Date().getTime());
		return String.format(format, ToUserName, RcvToken.WECHAT_CORP_ID, createTime, "text", content);
	}	
}
